<template>
  <!-- 设备配置--传感器配置 -->
  <div class="app-container table-flex-wrapper device-config-page">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="" prop="grade">
        <el-select class="select1" v-model="queryParams.sensorTypeId" placeholder="请选择传感器类型" clearable size="small"
          >
          <el-option v-for="dict in optionsFrom.typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.deviceName" placeholder="模糊搜索传感器名称" clearable size="small"  />
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.deviceNumber" placeholder="模糊搜索传感器编号" clearable size="small"  />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" @click="handleQuery" type="primary">搜索</el-button>
        <el-button size="mini" @click="handleAdd" type="primary">新增</el-button>
        <el-button size="mini" @click="handleImport" type="primary">批量导入</el-button>
        <el-button size="mini" @click="handleExport" type="primary">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" size="mini" :data="sensorList" @selection-change="handleSelectionChange"
      :header-cell-style="changeTableHeaderStyle">
      <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="monitorDetail" width="110" label="监测内容" align="center" ></el-table-column>
      <el-table-column prop="sensorTypeId" width="90" label="传感器类型" align="center" :formatter="typeFormat"></el-table-column>
      <el-table-column prop="device.deviceName" width="150" label="传感器名称" align="center"></el-table-column>
      <el-table-column prop="device.number" width="90" label="传感器编号" align="center"></el-table-column>
      <el-table-column prop="device.imei" min-width="110" show-overflow-tooltip label="通信设备IMEI" align="center"></el-table-column>
      <el-table-column prop="device.point.pointName" min-width="120" label="测点名称" align="center"></el-table-column>
      <el-table-column prop="device.point.lat" label="经度" width="100px" align="center"></el-table-column>
      <el-table-column prop="device.point.lon" label="纬度" width="100px" align="center"></el-table-column>
      <el-table-column label="是否启用" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.device.isValid" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="阈值" align="center">
        <el-table-column width="80" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡可能性小,请密切观测" placement="top" effect="dark">
              <span style="color: #3492FC">一级
                <!--<i class="el-icon-question el-icon&#45;&#45;right"></i>-->
              </span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #3492FC">{{ scope.row.monitorItems.length>0?scope.row.monitorItems[0].threshold1:'-' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="80" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡的可能性较大,请各岗位人员到岗待命" placement="top" effect="dark">
              <span style="color: #FF8000">二级</span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #FF8000">{{ scope.row.monitorItems.length>0?scope.row.monitorItems[0].threshold2 :'-'}}</span>
          </template>
        </el-table-column>
        <el-table-column width="80" align="center">
          <template slot="header">
            <el-tooltip content="发生山体滑坡的可能性很大,及时采取人员介入,封锁相应道路" placement="top" effect="dark">
              <span style="color: #ff0000">三级</span>
            </el-tooltip>
          </template>
          <template scope="scope">
            <span style="color: #ff0000">{{ scope.row.monitorItems.length>0?scope.row.monitorItems[0].threshold3 :'-'}}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="operation" label="操作" align="center" class-name="small-padding fixed-width" min-width="140">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">编辑</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.sensorId)" v-hasPermi="['slope:sensor:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <Add ref="add" @refresh="getList"></Add>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          传感器只允许新增，若已存在不允许覆盖
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listSensorType } from "@/api/slope/sensorType.js";
  import { changeDeviceIsValid } from "@/api/slope/device.js";
  import { getToken } from "@/utils/auth";
  import Add from "./add";
  import { importTemplate, importSensor, changeIsValid, deleteSensor } from "@/api/slope/sensor.js";

  import { listSensor,listSensorConfiguration, getSensorConfiguration, updateSensor, exportSensorConfiguration, sensorChangeStatus } from "@/api/page/device.js";
  export default {
    name: "equipment",
    components: {
      Add
    },
    data() {
      return {
        // 屏幕宽
        screenWidth: document.body.clientWidth,
        // 屏幕高
        screeHeight: document.body.clientHeight,
        tableHeight: 400,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sensorTypeId:null,
          deviceName:"",
          deviceNumber:null,
          // deviceState:null
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        optionsFrom: {
          typeOptions: [],
          statusOptions: []
        },
        sensorList:[],
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/slope/sensor/importData"
        },
        // 导出加载框
        exportLoading: {
          lock: true,
          text: '正在导出文件，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        },
      };
    },
    created() {
      let self = this;
      self.getList();
      listSensorType().then(response=>{
        self.optionsFrom.typeOptions=[];
        for(let i=0;i<response.rows.length;++i){
          let dict={
            dictLabel:response.rows[i].typeName,
            dictValue:response.rows[i].sensorTypeId
          }
          self.optionsFrom.typeOptions.push(dict);
        }
      }).catch((error)=>{
        console.log(error);
      });
      self.getDicts("sensor_state").then(response => {
        self.optionsFrom.statusOptions = response.data;
      }).catch((error)=>{
        console.log(error);
      });
      //通过判断浏览器宽度来改变table和chart的高度
      if (this.screenWidth > 1440) {
        this.tableHeight = 600;
      }
    },
    methods: {
      /**
       * 删除传感器信息
       * @param id 传感器id
       */
      deleteInfo(id) {
        let self = this;
         self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            deleteSensor(id).then(res=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            });
          })
          .then(() => {
            self.getList();
          })
          .catch(function(e) {
        });
      },
      /** 查询传感器列表 */
      getList() {
        let self = this;
        self.loading = true;
        listSensorConfiguration(self.addDateRange(self.queryParams, self.dateRange)).then(response => {
          self.sensorList=response.rows;
          self.total = response.total;
          self.loading = false;
          console.log(self.sensorList);
        }).catch((error)=>{
          self.loading = false;
          console.log(error);
        });
      },

      typeFormat(row, column) {
        return this.selectDictLabel(this.optionsFrom.typeOptions, row.sensorTypeId);
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$refs.add.handleClick({
          title: "添加传感器",
          submit: this.handleSubmit
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.$refs.add.handleClick({
          info: row,
          title: "编辑传感器",
          submit: this.handleSubmit
        });
      },
      /** 启用按钮操作 */
      handleStatusChange(row) {
        let self = this;
        let text = row.device.isValid === "0" ? "启用" : "停用";
        self.$confirm( '确认要"' + text + '""' + row.device.deviceName + '"设备吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(function() {
            let data = {
              "sensorId":row.sensorId,
              "device": {
                "deviceId":row.deviceId,
                "isValid": row.device.isValid
              }
            };
            changeIsValid(data).then(res => {
              if (res != undefined && res.code == 200) {
                self.msgSuccess(text + "成功");
              } else {
                if (row.device.isValid == "0") {
                  row.device.isValid = "1";
                } else {
                  row.device.isValid = "0";
                }
              }
            });
          })
          .catch(function() {
            if (row.device.isValid == "0") {
              row.device.isValid = "1";
            } else {
              row.device.isValid = "0";
            }
          });
      },

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "传感器导入";
        this.upload.open = true;
      },
      /** 导出按钮操作 */
      handleExport() {
        let self = this;
        let loading = undefined;
        const queryParams = self.queryParams;
        self.$confirm("是否确认导出所有数据?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            loading = self.$loading(self.exportLoading);
            return exportSensorConfiguration(queryParams);
          }).then(response => {
            this.download(response.msg);
            self.msgSuccess("导出成功");
            loading.close();
          }).catch(function() {
            if (loading!=undefined) {
              loading.close();
            }
          });
      },
      /** 下载模板操作 */
      importTemplate() {
        let self = this;
        let loading = self.$loading(self.exportLoading);
        importTemplate().then(response => {
          this.download(response.msg);
          loading.close();
        }).catch((error)=>{
          loading.close();
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {
          dangerouslyUseHTMLString: true
        });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      readyHandle(map, mapComp) {
        this.olMap = map;
      },

      /** 修改table头部样式 */
      changeTableHeaderStyle({ row, column, rowIndex, columnIndex }) {
        if (row.length == 3 && rowIndex == 1 && columnIndex == 0) {
          return "color: #3492FC;";
        } else if (row.length == 3 && rowIndex == 1 && columnIndex == 1) {
          return "color: #FF8000;";
        } else if (row.length == 3 && rowIndex == 1 && columnIndex == 2) {
          return "color: #FF0000;";
        }
      },
      /** 修改弹框样式 */
      updateDialogStyle() {
        let self = this;
        let bodyWidth = window.innerWidth; // 浏览器宽度
        let elRowWidth = bodyWidth * 0.9 - 20 * 2 - -10 * 2; // 弹框el-row宽度  弹框的：padding:30px 20px el-row的：margin: 0px -10px
        let onceElColWidth = elRowWidth / 4 - 10 * 2; // 一对el-col宽度 平均分为4分 el-col带有padding: 0px 10px;
        let labelWidth = onceElColWidth * 0.25; // 表头宽度 取6/24
        let alignWidth = onceElColWidth + 160 + 10 * 2; // 阈值值宽度 一个el-col去掉表头，加一个表头，加上第一个的右边距10px，第二个的左边距10px
        setTimeout(function() {
          // 解决vue比element先执行问题
          // console.log(self.$refs.testGetElementRow);
          self.$refs.setAlarmWidth.style.width = labelWidth + "px";
          self.$refs.setAlarmValueWidth.style.width = alignWidth + "px";
          // console.log(bodyWidth,elRowWidth,onceElColWidth, self.$refs.setAlarmWidth.style.width, self.$refs.setAlarmValueWidth.style.width);
        }, 0);
      }
    }
  };
</script>
<style lang="scss">
  @import "./config.scss";
</style>
